package com.beerandjesus.sportofkings.handicapper.migration.hibernate;

import org.hibernate.SessionFactory;
import org.springframework.aop.support.annotation.AnnotationClassFilter;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Date: 3/24/15
 * Time: 8:57 PM
 */
public class MigrationService {

    private SessionFactoryBuilder sessionFactoryBuilder;
    private AnnotationClassFilter annotationClassFilter;
    private HibernateCopier copier;
    private HibernateConfig configFrom;
    private HibernateConfig configTo;

    public MigrationService(SessionFactoryBuilder sessionFactoryBuilder,
                            AnnotationClassFilter annotationClassFilter,
                            HibernateCopier copier,
                            HibernateConfig configFrom,
                            HibernateConfig configTo) {
        this.sessionFactoryBuilder = sessionFactoryBuilder;
        this.annotationClassFilter = annotationClassFilter;
        this.copier = copier;
        this.configFrom = configFrom;
        this.configTo = configTo;
    }

    public void migratePackage(File packageFile) throws ClassNotFoundException, IOException {
        File[] files = packageFile.listFiles(new FilenameFilter() {
            public boolean accept(File file, String s) {
                return s.endsWith(".java");
            }
        });
        List<Class<?>> entities = new ArrayList<Class<?>>();
        for (File file : files) {
            Class<?> aClass = getClassForJavaFile(file);
            if (annotationClassFilter.matches(aClass)) {
                entities.add(aClass);
            }
        }
        SessionFactory sessionFactoryFrom = sessionFactoryBuilder.buildSessionFactory(entities, configFrom);
        SessionFactory sessionFactoryTo = sessionFactoryBuilder.buildSessionFactory(entities, configTo);
        for (Class<?> entity : entities) {
            copier.copy(entity, sessionFactoryFrom.getCurrentSession(), sessionFactoryTo.getCurrentSession());
        }
    }

    private Class<?> getClassForJavaFile(File file) throws IOException, ClassNotFoundException {
        String[] split = file.getCanonicalPath().split("\\.java");
        String fileName = split[0];
        String substring = fileName.substring(fileName.indexOf("/com/") + 1, fileName.length());
        String theFile = substring.replace("/", ".");
        return Class.forName(theFile);
    }
}
